package org.zhang.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.zhang.shortlink.admin.common.biz.user.UserContext;
import org.zhang.shortlink.admin.common.convention.exception.ClientException;
import org.zhang.shortlink.admin.common.enums.UserErrorCodeEnum;
import org.zhang.shortlink.admin.dao.entity.UserDo;
import org.zhang.shortlink.admin.dao.mapper.UserMapper;
import org.zhang.shortlink.admin.dto.request.UserLoginReqDTO;
import org.zhang.shortlink.admin.dto.request.UserRegisterReqDTO;
import org.zhang.shortlink.admin.dto.request.UserUpdateReqDTO;
import org.zhang.shortlink.admin.dto.response.UserLoginRespDTO;
import org.zhang.shortlink.admin.dto.response.UserRespDto;
import org.zhang.shortlink.admin.service.GroupService;
import org.zhang.shortlink.admin.service.UserService;

import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.zhang.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static org.zhang.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static org.zhang.shortlink.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDo> implements UserService {
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate redisTemplate;
    private final GroupService groupService;

    @Override
    public UserRespDto getUserByUsername(String username) {
        LambdaQueryWrapper<UserDo> queryWrapper = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername, username);
        UserDo userDo = baseMapper.selectOne(queryWrapper);
        if (userDo == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDto userRespDto = new UserRespDto();
        BeanUtils.copyProperties(userDo, userRespDto);
        return userRespDto;
    }

    @Override
    public Boolean hasUserName(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO userRegisterReqDTO) {
        //判断用户名是否存在
        if (!hasUserName(userRegisterReqDTO.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + userRegisterReqDTO.getUsername());
        if (!lock.tryLock()){
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int inserted = baseMapper.insert(BeanUtil.toBean(userRegisterReqDTO, UserDo.class));
            if (inserted < 1) {
                throw new ClientException(USER_SAVE_ERROR);
            }
            //用户信息添加进布隆过滤器
            userRegisterCachePenetrationBloomFilter.add(userRegisterReqDTO.getUsername());
            //为用户新增默认短链接分组
            groupService.saveGroup(userRegisterReqDTO.getUsername(), "默认分组");
        }catch (DuplicateKeyException ex){
            throw new ClientException(USER_EXIST);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        if (!Objects.equals(userUpdateReqDTO.getUsername(), UserContext.getUsername())) {
            throw new ClientException("当前登录用户修改请求异常");
        }
        LambdaUpdateWrapper<UserDo> eq = Wrappers.lambdaUpdate(UserDo.class).eq(UserDo::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.toBean(userUpdateReqDTO, UserDo.class), eq);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDo> eq = Wrappers.lambdaQuery(UserDo.class).eq(UserDo::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDo::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDo::getDelFlag, 0);
        UserDo user = baseMapper.selectOne(eq);
        if (user == null) {
            throw new ClientException("用户不存在");
        }
        Map<Object ,Object> hasLoginMap = redisTemplate.opsForHash().entries(USER_LOGIN_KEY  + userLoginReqDTO.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            redisTemplate.expire(USER_LOGIN_KEY + userLoginReqDTO.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForHash().put(USER_LOGIN_KEY  + userLoginReqDTO.getUsername(), uuid, JSON.toJSONString(user));
        redisTemplate.expire(USER_LOGIN_KEY  + userLoginReqDTO.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }


        @Override
        public Boolean checkLogin(String username, String token) {
            return redisTemplate.opsForHash().get(USER_LOGIN_KEY  + username, token) != null;
        }

        @Override
        public void logout(String username, String token) {
            if (checkLogin(username, token)) {
                redisTemplate.delete(USER_LOGIN_KEY  + username);
                return;
            }
            throw new ClientException("用户Token不存在或用户未登录");
        }
}
